<?php
namespace app\common\service;

use app\common\model\OrderAddrModel;
use app\common\model\OrderGoodsModel;
use app\common\model\OrderModel;
use GuzzleHttp\Exception\RequestException;

//活动
class MaBangErp{
    const CURRENCY = 'USD';
    public static function createOrder(OrderModel $order_model)
    {
        if(empty($order_model['is_pay'])) throw new \Exception("未支付订单无法同步");
        $order_model_addr = OrderAddrModel::where(['oid'=>$order_model['id']])->find();
        if(empty($order_model_addr)) throw new \Exception("订单地址异常无法同步");
        $data = [
            //订单编号
            'platformOrderId'=> $order_model['no'],
            //店铺名称
            'shopName'=> Config::maBangErp('shop_name'),
            //买家编号
            'buyerUserId'=> empty($order_model['uid'])?'session':$order_model['uid'],
            //买家名称
            'buyerName'=> $order_model_addr['first_name']." ".$order_model_addr['last_name'],
            //买家电话一
            'phone1'=> $order_model_addr['phone'],
            //买家国家二字码，填写时country可不写
//            'country'=>$order_model_addr['country'],
            'countryCode'=>$order_model_addr['country'],
            //买家所属区域
            'district'=> empty($order_model_addr['district'])?'':$order_model_addr['district'],
            //买家所在省份
            'province'=> empty($order_model_addr['state'])?'':$order_model_addr['state'],
            //买家所在城市
            'city'=> empty($order_model_addr['city'])?'':$order_model_addr['city'],
            //买家地址一
            'street1'=> empty($order_model_addr['street'])?'':$order_model_addr['street'],
            //买家地址一
//            'street2'=>'test-street2',
            //买家邮箱
            'email'=> empty($order_model['email'])?'':$order_model['email'],
            //买家邮编
            'postCode'=> empty($order_model_addr['postcode'])?'':$order_model_addr['postcode'],
            //订单币种
            'currencyId'=> self::CURRENCY,
            //优惠金额
            'voucherPrice'=> empty($order_model['dis_money'])?'':$order_model['dis_money'],
            //邮费
            'shippingFee'=> empty($order_model['freight_money'])?'':$order_model['freight_money'],
            //平台费
            'platformFee'=> '',
            //商品总售价，如果填写值，将不按照商品售价计算
            'itemTotal'=>  empty($order_model['goods_money'])?'':$order_model['goods_money'],
            //其他收入
            'otherIncome'=>  empty($order_model['tip_money'])?'':$order_model['tip_money'],
            //其他支出
            'otherExpend'=> '',
            //付款时间
            'paidTime'=> empty($order_model['pay_time'])?'':$order_model['pay_time'],
            //支付方式
            'paymentName'=> empty($order_model['pay_way'])?'':$order_model['pay_way'],
            //10.cod订单 11.wish WE订单
            'codflag'=> '',
            //paypal编号
            'paypalId'=> empty($order_model['paypal_orderid'])?'':$order_model['paypal_orderid'],
            //商品信息[{
            //  "title": "商品标题", // 必填
            //  "platformSku": "平台原始SKU", // 必填
            //  "quantity", "商品数量", // 必填
            //  "pictureUrl", "商品图片,没有按照商品对应的数据", // 必填
            //  "itemId", "平台订单商品交易编号",
            //  "sellPrice", "商品售价",
            //  "productUnit", "产品单位",
            //  "specifics", "商品多属性",
            //  "message", "商品留言",
            //  "productUrl", "商品链接",
            //  "salesRecordNumber", "商品交易号，指定平台需要可以根据业务判断",
            //}]
            'orderItemList'=> '',
        ];
        $orderItemList = [];
        OrderGoodsModel::where(['oid'=>$order_model['id']])->select()->each(function($item,$index)use(&$orderItemList){
            array_push($orderItemList,[
                "title"=>$item['name'],// "商品标题", // 必填
                "platformSku"=>$item['sku_name'],// "平台原始SKU", // 必填
                "quantity"=>$item['num'],// "商品数量", // 必填
                "pictureUrl"=>$item['img'],// "商品图片,没有按照商品对应的数据", // 必填
                "itemId"=>$item['id'],// "平台订单商品交易编号",
                "sellPrice"=>$item['price'],// "商品售价",
                "productUnit"=>"",// "产品单位",
                "specifics"=>"{$item['gno']}_{$item['gcode']}_{$item['sku_name']}_{$index}",// "商品多属性",
                "message"=>"{$item['cond_remark']}",// "商品留言",
                "productUrl"=>request()->domain()."/products?id=".$item['gid'],// "商品链接",
                "salesRecordNumber"=>$item['id'],// "商品交易号，指定平台需要可以根据业务判断",
            ]);
        });
        $data['orderItemList'] = $orderItemList;
//        dump($orderItemList);exit;
        $result = self::req('order-do-create-order',$data);

        if($order_model['mb_state']!=200 && isset($result['code'])){
            $order_model->setAttrs([
                'mb_state'=>$result['code'],
                'mb_create_time'=> date('Y-m-d H:i:s'),
                'mb_result'=> json_encode($result,JSON_UNESCAPED_UNICODE),
                'mb_change_record'=> json_encode([$result],JSON_UNESCAPED_UNICODE),
            ]);
        }else{
            $order_model->setAttrs([
                'mb_create_time'=> date('Y-m-d H:i:s'),
            ]);
        }
        $order_model->save();
        return $order_model;
    }


    public static function modifyOrder(OrderModel $order_model,array $input_data)
    {
        $data = array_merge([
            //订单编号
            'platformOrderId'=> $order_model['no'],


        ],$input_data);
        $result = self::req('order-do-change-order',$data);


        return $result;
    }


    public static function req($api,array $data=[],$url="https://gwapi.mabangerp.com/api/v2",$method="POST"){
        $data = [
            'api'=>$api,
            'appkey'=>Config::maBangErp('key'),
            'data'=>$data,
            'timestamp'=>(string)time(),
        ];
//        dump($data);
        $json_data = json_encode($data);
//        dump('json字符串'.$json_data.PHP_EOL.'开发者密钥:'.Config::maBangErp('secret').PHP_EOL.'生成的签名:'.hash_hmac("sha256",$json_data,Config::maBangErp('secret')));
        try{
            $client = new \GuzzleHttp\Client();
            $options = [
                'body' => $json_data,
                'verify'=>false,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => hash_hmac("sha256",$json_data,Config::maBangErp('secret')),
                ]
            ];
            $response = $client->request($method, $url, $options);
            $result = $response->getBody()->getContents(); // '{"id": 1420053, "name": "guzzle", ...}'
        }catch (RequestException $e){
            $result = $e->getResponse()->getBody()->getContents();
        }catch (\Exception $e){
            $result = "{'errmsg':'{$e->getmessage()}'}";
        }

        $result = empty($result)?[]:json_decode($result,true);
        return $result;

    }

}